<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/2/21 0021
 * Time: 17:20
 */

namespace app\api\service;


use xhadmin\CommonService;
use app\backend\model\SysSite;
use EasyWeChat\Factory;

class PaymentService extends CommonService
{
    protected static $config = [];
    protected static $PayApp;
    
    public function __construct()
    {
    
    
    }
    
    public static function instance($wxapp_id,$type=''): PaymentService
    {
        $site = SysSite::where(['wxapp_id'=>$wxapp_id])->find();
        if($type=='H5-wx'){
            $appId = $site['official_account_appid'];
        }elseif($type=='app'){
            $appId = $site['app_app_id'];
        }else{
            $appId = $site['app_id'];
        }
        self::$config = [
            'app_id'    => $appId,
            'mch_id'    => $site['mch_id'],
            'key'       => $site['mch_key'],   // API 密钥
            'cert_path' => app()->getRootPath(). 'public/' .$site['cert_path'], // XXX: 绝对路径！！！！
            'key_path'  => app()->getRootPath(). 'public/' .$site['key_path'],
        ];
        
        self::$PayApp = Factory::payment(self::$config);
        
        
        return new self();
    }
    
    public static function create($openid, $order_no, $total_fee, $title, $params,$trade_type="JSAPI")
    {
        if($trade_type == "APP"){
            $result = self::$PayApp->order->unify([
                'body'         => $title,
                'out_trade_no' => $order_no,
                'total_fee'    => intval($total_fee *100),
                'notify_url'   => $params['notify_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type'   => $trade_type, // 请对应换成你的支付方式对应的值类型
            ]);
        }else{
            $result = self::$PayApp->order->unify([
                'body'         => $title,
                'out_trade_no' => $order_no,
                'total_fee'    => intval($total_fee *100),
                'notify_url'   => $params['notify_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type'   => $trade_type, // 请对应换成你的支付方式对应的值类型
                'openid'       => $openid,
            ]);
        }
        
        
        if ($result['return_code'] == 'SUCCESS') {
            if ($result['result_code'] == 'SUCCESS') {
               
                if($trade_type == 'JSAPI'){
                    $jssdk = self::$PayApp->jssdk;
                    
                    $pay_data = $jssdk->sdkConfig($result['prepay_id']);
                }elseif($trade_type == 'APP'){
                    $jssdk = self::$PayApp->jssdk;
                    $pay_data = $jssdk->appConfig($result['prepay_id']);
                    
                }else{
                    $pay_data = $result['mweb_url'];
                }
                
                return $pay_data;
            } else {
                throw new \Exception($result['err_code_des']);
                
            }
        } else {
            throw new \Exception($result['return_msg']);
        }
    }
    
    public static function refund($order_no,$refund_no,$totalFee,$refundFee){
        
        $result = self::$PayApp->refund->byOutTradeNumber($order_no,$refund_no,intval($totalFee*100),intval($refundFee*100),[]);
        
        if ($result['return_code'] == 'SUCCESS') {
            if ($result['result_code'] == 'SUCCESS') {
                return $result;
            } else {
                throw new \Exception($result['err_code_des']);
            }
        } else {
            throw new \Exception($result['return_msg']);
        }
    }
    
    public static function tixain($order_no,$openid,$totalFee,$title){
        $result = self::$PayApp->transfer->toBalance([
            'partner_trade_no' => $order_no, // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
            'openid'           => $openid,
            'check_name'       => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
            're_user_name'     => '', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
            'amount'           => intval($totalFee * 100), // 企业付款金额，单位为分
            'desc'             => $title, // 企业付款操作说明信息。必填
        ]);
        if ($result['return_code'] == 'SUCCESS') {
            if ($result['result_code'] == 'SUCCESS') {
                return $result;
            } else {
                throw new \Exception($result['return_msg']);
            }
        } else {
            throw new \Exception($result['return_msg']);
        }
    }
    
    /**
     * @return array
     */
    public static function getConfig(): array
    {
        return self::$config;
    }
    
    /**
     * @return mixed
     */
    public static function getPayApp()
    {
        return self::$PayApp;
    }
    
    
}